package com.juyu.miliao.api.service;

import com.juyu.miliao.api.constant.EnergyLevelType;
import com.juyu.miliao.api.dao.mysql.BillDetailDao;
import com.juyu.miliao.api.dao.mysql.BuyLimitDao;
import com.juyu.miliao.api.domain.BuyLimit;
import com.juyu.miliao.common.constant.BeansType;
import com.juyu.miliao.common.domain.BillDetailBeans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * @ClassName: BuyLimitService
 * @Description: TODO
 * @Author zhangcheng
 * @Date 19-9-12下午3:08
 */
@Service
public class BuyLimitService {
    private final Logger buyLimitLogger = LoggerFactory.getLogger("buyLimit");
    @Resource
    private BuyLimitDao buyLimitDao;
    @Resource
    private EnergyLevelService energyLevelService;
    @Resource
    private BillDetailDao billDetailDao;
    @Resource
    private UserWalletService userWalletService;

    public List<BuyLimit> listBuyLimit(LocalDateTime time, Integer state) {
        List<BuyLimit> buyLimitList =  buyLimitDao.listBuyLimit(time, state);
        buyLimitList.forEach(buyLimit -> {
                    long remainingTime = buyLimit.getEndTime().toEpochSecond(ZoneOffset.ofHours(8)) - Instant.now().getEpochSecond();
                    if (remainingTime < 0) {
                        remainingTime = 0;
                    }
                    buyLimit.setRemainingTime(remainingTime);
                });
        return buyLimitList;
    }

    /**
     * 购买限时抢购
     *
     * @param
     */
    public void buy(Long userId, BuyLimit buyLimit) {
        //更新用户钱包
        userWalletService.addBeans(userId, buyLimit.getBeans());
        //更新明细
        BillDetailBeans billDetailBeans = new BillDetailBeans();
        billDetailBeans.setBeansType(BeansType.BUY_LIMIT.getCode());
        billDetailBeans.setBeans(buyLimit.getBeans());
        billDetailBeans.setRatio(0);
        billDetailBeans.setUserId(userId);
        billDetailDao.insertBillDetailBeans(billDetailBeans);
        //更新用户能量
        energyLevelService.addUserEnergyLevel(userId, EnergyLevelType.ENERGY_TYPE_BUY_LIMIT, (int) (long) buyLimit.getEnergy());
        buyLimit.setBoughtNum(1L);
        buyLimitDao.updateBuyLimit(buyLimit);
    }

}
